import {Component, ElementRef, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd';
import {getFakeChartData} from '../../../../_mock/chart.service';
import {_HttpClient} from "@core/services/http.client";
import {HttpParams} from "@angular/common/http";
import {getRule, saveRule, removeRule} from '../../../../_mock/rule.service';
import index from "@angular/cli/lib/cli";
import {Subscription} from "rxjs/Subscription";
import {ServerSocket} from "@core/services/ws.service";
import {BaseOptions} from "ng-zorro-antd/src/modal/nz-modal-options.provider";

declare var jsPlumb: any;

@Component({
    selector: 'app-flow',
    templateUrl: './flow.component.html',
    styleUrls: ['./flow.component.css'],

    encapsulation: ViewEncapsulation.None
})
export class FlowComponent implements OnInit {

    //modal props
    modalStyle = {
        top: '300px'
    }
    @ViewChild('fuck') elementView: ElementRef;

    isVisibleMiddle = false;
    modalTitle = ""
    modalImgPath = "";
    modalTypeSelector = ""
    typeOptions = [
        {value: 'fixed', label: '固定'},
        {value: 'percent', label: '比例'},
        {value: 'remain', label: '剩余'}
    ];

    @ViewChild('canvas')
    canvas;

    editor_panel_style = {transform: 'scale(1)', left: '0px', top: '0px'};

    //dragment
    zoomindex = 10;
    canvasLeft = 0;
    canvasTop = 0;
    translateX = 0;
    translateY = 0;
    dragFlag = false;
    reLeft = 0
    reTop = 0
    resizeFlag = false;

    //node
    dragOverClass = " window jtk-node jtk-drag jtk-dragged"
    normalClass = " window jtk-node"

    //current node
    selectedNode = -1;
    addNodeType;


    ngOnInit(): void {

    }
dataTEMP=[
    {
        "id": "1111",
        "type": "start",
        "text": "开始",
        "node_id": [
            "1112"
        ],
        "group_id": "-1",
        "style": {

        },
        "props": {

        }
    },
    {
        "id": "1112",
        "type": "start",
        "text": "事件起因",
        "node_id": [
            "1121,1131,1141"
        ],
        "group_id": "-1",
        "style": {

        },
        "props": {

        }
    },
    {
        "id": "g1",
        "type": "group",
        "text": "辉发牛奶企业",
        "nodes": [
            {
                "id": "1121",
                "type": "fork",
                "text": "第一次决策",
                "node_id": [
                    "11211",
                    "11212",
                    "11213",
                    "11214",
                    "11215",
                    "11216"
                ],
                "group_id": "g1",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11211",
                "type": "process",
                "text": "场景一",
                "node_id": [
                    "112111"
                ],
                "group_id": "g1",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "112111",
                "type": "process",
                "text": "事件1",
                "node_id": [
                    "000"
                ],
                "group_id": "g1",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11212",
                "type": "process",
                "text": "场景一",
                "node_id": [
                    "112121"
                ],
                "group_id": "g1",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "112121",
                "type": "process",
                "text": "事件2",
                "node_id": [
                    "000"
                ],
                "group_id": "g1",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11213",
                "type": "process",
                "text": "事件1",
                "node_id": [
                    "000"
                ],
                "group_id": "g1",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11214",
                "type": "process",
                "text": "事件2",
                "node_id": [
                    "000"
                ],
                "group_id": "g1",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11215",
                "type": "process",
                "text": "事件1",
                "node_id": [
                    "000"
                ],
                "group_id": "g1",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11216",
                "type": "process",
                "text": "事件2",
                "node_id": [
                    "000"
                ],
                "group_id": "g1",
                "style": {

                },
                "props": {

                }
            }
        ],
        "style": {

        },
        "props": {
            "group_text": "辉发牛奶企业",
            "group_img": "img_huifa.png",
            "group_type": "fixed",
            "group_limit": "7"
        }
    },
    {
        "id": "g2",
        "type": "group",
        "text": "三特燕麦企业",
        "nodes": [
            {
                "id": "1131",
                "type": "fork",
                "text": "第一次决策",
                "node_id": [
                    "11311",
                    "11312",
                    "11313",
                    "11314",
                    "11315",
                    "11316"
                ],
                "group_id": "g2",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11311",
                "type": "process",
                "text": "场景二",
                "node_id": [
                    "113111"
                ],
                "group_id": "g2",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "113111",
                "type": "process",
                "text": "事件1",
                "node_id": [
                    "000"
                ],
                "group_id": "g2",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11312",
                "type": "process",
                "text": "场景二",
                "node_id": [
                    "113121"
                ],
                "group_id": "g2",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "113121",
                "type": "process",
                "text": "事件2",
                "node_id": [
                    "000"
                ],
                "group_id": "g2",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11313",
                "type": "process",
                "text": "事件1",
                "node_id": [
                    "000"
                ],
                "group_id": "g2",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11314",
                "type": "process",
                "text": "事件2",
                "node_id": [
                    "000"
                ],
                "group_id": "g2",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11315",
                "type": "process",
                "text": "事件1",
                "node_id": [
                    "000"
                ],
                "group_id": "g2",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11316",
                "type": "process",
                "text": "事件2",
                "node_id": [
                    "000"
                ],
                "group_id": "g2",
                "style": {

                },
                "props": {

                }
            }
        ],
        "style": {

        },
        "props": {
            "group_text": "三特燕麦企业",
            "group_img": "img_sante.png",
            "group_type": "fixed",
            "group_limit": "7"
        }
    },
    {
        "id": "g3",
        "type": "group",
        "text": "政府",
        "nodes": [
            {
                "id": "1141",
                "type": "fork",
                "text": "第一次决策",
                "node_id": [
                    "11411",
                    "11412"
                ],
                "group_id": "g3",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11411",
                "type": "process",
                "text": "场景三",
                "node_id": [
                    "114111"
                ],
                "group_id": "g3",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "114111",
                "type": "process",
                "text": "事件1",
                "node_id": [
                    "000"
                ],
                "group_id": "g3",
                "style": {

                },
                "props": {

                }
            },
            {
                "id": "11412",
                "type": "process",
                "text": "事件2",
                "node_id": [
                    "000"
                ],
                "group_id": "g3",
                "style": {

                },
                "props": {

                }
            }
        ],
        "style": {

        },
        "props": {
            "group_text": "政府",
            "group_img": "img_zhengfu.png",
            "group_type": "fixed",
            "group_limit": "9"
        }
    },
    {
        "id": "g4",
        "type": "group",
        "text": "群众",
        "nodes": [

        ],
        "style": {

        },
        "props": {
            "group_text": "群众",
            "group_img": "img_qunzhong.png",
            "group_type": "remain",
            "group_limit": "9999"
        }
    },
    {
        "id": "000",
        "type": "end",
        "text": "结束",
        "nodes": [

        ],
        "style": {

        },
        "props": {

        }
    }
];
    data: any[] = [
        {
            id: '111',
            type: 'start',
            text: '开始',
            node_id: ['112'],
            project_id: '',
            group_id: '-1',
            parent_id: '',
            scene_id: '111',
            style: {},
            props: {}
        },
        {
            id: '112',
            type: 'process',
            text: '场景1',
            node_id: ['113'],
            project_id: '',
            group_id: '-1',
            parent_id: '1',
            scene_id: '112',
            style: {},
            props: {}
        },
        {
            id: '113',
            type: 'fork',
            text: '分支1',
            node_id: ['114', '5'],
            project_id: '',
            group_id: '-1',
            parent_id: '1',
            scene_id: '113',
            style: {},
            props: {}
        },
        {
            id: '5',
            type: 'process',
            text: '场景5',
            node_id: [''],
            project_id: '',
            group_id: '-1',
            parent_id: '1',
            scene_id: '5',
            style: {},
            props: {}
        },
        {
            id: '114',
            type: 'process',
            text: '场景2',
            node_id: ['120'],
            project_id: '',
            group_id: '-1',
            parent_id: '3',
            scene_id: '114',
            style: {},
            props: {}
        },
        {
            id: 'g1',
            type: 'group',
            text: '分组1',
            nodes: [
                {
                    id: '120',
                    type: 'fork',
                    text: '分组逻辑分支1',
                    node_id: ['115','116','118'],
                    project_id: '',
                    group_id: 'g1',
                    parent_id: '',
                    scene_id: '120',
                    style: {},
                }, {
                    id: '115',
                    type: 'process',
                    text: '分组场景2',
                    node_id: [],
                    project_id: '',
                    group_id: 'g1',
                    parent_id: 'gs1',
                    scene_id: '115',
                    style: {},
                }],

            project_id: '',
            group_id: '-1',
            parent_id: '1',
            scene_id: '1',
            style: {},
            props: {
                group_text: '固定配额分组',
                group_img: '',
                group_type: 'fixed',
                group_limit: '3',
            }
        }
        ,
        {
            id: 'g2',
            type: 'group',
            text: '分组2',
            nodes: [{
                id: '116',
                type: 'process',
                text: '分组场景21',
                node_id: ['117'],
                project_id: '',
                group_id: 'g2',
                parent_id: '3',
                scene_id: '116',
                style: {},
            }, {
                id: '117',
                type: 'process',
                text: '分组场景22',
                node_id: [''],
                project_id: '',
                group_id: 'g2',
                parent_id: '3',
                scene_id: '117',
                style: {},
            }],

            project_id: '',
            group_id: '-1',
            parent_id: '1',
            scene_id: '1',
            style: {},
            props: {
                group_text: '比例配额分组',
                group_img: '',
                group_type: 'percent',
                group_limit: '3',
            }
        },
        {
            id: 'g3',
            type: 'group',
            text: '分组3',
            nodes: [{
                id: '118',
                type: 'process',
                text: '分组场景31',
                node_id: ['119'],
                project_id: '',
                group_id: 'g3',
                parent_id: '3',
                scene_id: '118',
                style: {},
            }, {
                id: '119',
                type: 'process',
                text: '分组场景32',
                node_id: [''],
                project_id: '',
                group_id: 'g3',
                parent_id: '3',
                scene_id: '119',
                style: {},
            }],

            project_id: '',
            group_id: '-1',
            parent_id: '1',
            scene_id: '1',
            style: {},
            props: {
                group_text: '剩余配额分组',
                group_img: '',
                group_type: 'remain',
                group_limit: '3',
            }
        },

        {
            id: '6',
            type: 'event',
            text: '事件',
            node_id: [''],
            project_id: '',
            group_id: '-1',
            parent_id: '',
            scene_id: '6',
            style: {},
            props: {}
        }
    ]
    base_zindex = 999;
    el_nodes: any[] = [

        {
            nodeClass: this.normalClass,
            style: {top: '500px', left: '500px', width: '200px', height: '100px', "z-index": this.base_zindex + 1},
            type: 'process',
            title: '测试'
        },
        {
            nodeClass: this.normalClass,
            style: {top: '300px', left: '300px', width: '200px', height: '100px', "z-index": this.base_zindex + 1},
            type: 'start',
            title: '测试'
        },

        {
            nodeClass: this.normalClass,
            style: {top: '700px', left: '700px', width: '200px', height: '100px', "z-index": this.base_zindex + 1},
            type: 'fork',
            title: '测试'
        }
    ]

    el_groups: any[] = [
        {
            nodeClass: this.normalClass,
            style: {top: '100px', left: '100px', width: '200px', height: '400px', 'background-color': 'transparent'},
            type: 'group',
            title: '测试'
        },
        {
            nodeClass: this.normalClass,
            style: {top: '600px', left: '800px', width: '200px', height: '400px', 'background-color': 'transparent'},
            type: 'group',
            title: '测试'
        }
    ]

    dragFromSider(ev) {
        this.addNodeType = ev;
    }

    onDragEnds(ev, index) {
        this.clearNodesCss()

    }

    clearNodesCss() {
        for (let node of this.el_nodes) {
            node.nodeClass = this.normalClass
        }
    }

    mDragOver(ev) {
        ev.preventDefault();
    }

    groupDragOver(index) {

        this.selectedNode = index
        this.el_nodes[index].nodeClass = this.dragOverClass
        // this. nodeClass='node_group window jtk-node jtk-drag jtk-dragged'
        // alert( this.dragOverFlag)
    }

    groupDragLeave(index) {
        this.selectedNode = index
        this.el_nodes[index].nodeClass = this.normalClass
        // this. nodeClass='node_group window jtk-node jtk-drag jtk-dragged'
        // alert( this.dragOverFlag)
    }

    groupAppend(ev, index) {
        this.selectedNode = index
        this.el_nodes[index].nodeClass = this.normalClass
        // this. nodeClass=
        ev.stopPropagation()
    }


    //node edit

    nodeEdit(index) {
        this.selectedNode = index

        this.isVisibleMiddle = true
    }

    moves(event) {
        if (this.resizeFlag) {

            return false
        }
        if (this.dragFlag) {
            this.translateX = event.screenX - this.canvasLeft;
            this.translateY = event.screenY - this.canvasTop;
            this.canvasLeft = event.screenX
            this.canvasTop = event.screenY
            var top = +this.canvas.nativeElement.style.top.replace("px", '');
            var left = +this.canvas.nativeElement.style.left.replace("px", '');

            var accLeft = this.translateX
            var accTop = this.translateY

            this.reLeft = left + Number.parseInt(accLeft.toString().split(".")[0])
            this.reTop = top + Number.parseInt(accTop.toString().split(".")[0])

            this.updateUi()

        }

    }

    resizeStart() {
        this.resizeFlag = true
        jsPlumb.setDraggable(jsPlumb.getSelector(".window"), false)
    }

    resizeEnd() {
        this.resizeFlag = false;
        jsPlumb.setDraggable(jsPlumb.getSelector(".window"), true)
        this.instance.repaintEverything(false)
    }

    dragPanel(event) {
        this.translateY = 0;
        this.translateX = 0;
        this.canvasLeft = event.screenX
        this.canvasTop = event.screenY
        this.dragFlag = true

        // console.log(event)
    }


    dragup() {
        this.dragFlag = false
        this.resizeFlag = false;
    }


    mouseWheelUpFunc() {

        if (this.zoomindex < 10) {
            this.zoomindex++
            this.updateUi()
        }

    }

    mouseWheelDownFunc() {
        if (this.zoomindex > 1) {
            this.zoomindex--
            this.updateUi()
        }

    }

    refresh() {
        this.zoomindex = 10;
        this.reTop = 0;
        this.reLeft = 0;
        this.updateUi()
    }

    modalClose() {
        this.isVisibleMiddle = false;
    }

    updateUi() {
        this.editor_panel_style = {
            transform: 'scale(' + this.zoomindex / 10 + ')', top: (this.reTop) + 'px',
            left: (this.reLeft) + 'px'
        }
    }

    constructor(public msg: NzMessageService, private http: _HttpClient, private ws: ServerSocket) {
    }

    instance;
    private socketSubscription: Subscription

    OnDestroy() {
        this.socketSubscription.unsubscribe()
    }

    ngAfterViewInit() {


        this.socketSubscription = this.ws.messages.subscribe((message: string) => {
        })
        // var jsPlumb = jsp.jsPlumb;
        this.instance = jsPlumb.getInstance({
            // default drag options
            DragOptions: {cursor: 'pointer', zIndex: 2000},
            // the overlays to decorate each connection with.  note that the label overlay uses a function to generate the label text; in this
            // case it returns the 'labelText' member that we set on each connection in the 'init' method below.
            ConnectionOverlays: [
                ["Arrow", {
                    location: 1,
                    visible: true,
                    width: 11,
                    length: 11,
                    id: "ARROW",

                }],
                ["Label", {
                    location: 0.5,
                    id: "label",
                    cssClass: "aLabel",
                    events: {
                        // connection.getOverlay("label")
                        tap: function () {
                            let label = prompt("请输入标签文字：");
                            this.setLabel(label);
                        }
                    }
                }]
            ],
            Container: "canvas"
        });

        var basicType = {
            connector: "FlowChart",
            paintStyle: {stroke: "#434e59", strokeWidth: 1},
            hoverPaintStyle: {stroke: "#434e59"},
            overlays: [
                "Arrow"
            ]
        };
        let instance = this.instance;
        instance.registerConnectionType("basic", basicType);

        // this is the paint style for the connecting lines..
        var connectorPaintStyle = {
                strokeWidth: 1,
                stroke: "#434e59",
                joinstyle: "round",
                outlineStroke: "#434e59",
                outlineWidth: 1
            },
            // .. and this is the hover style.
            connectorHoverStyle = {
                strokeWidth: 1,
                stroke: "#434e59",
                outlineWidth: 1,
                outlineStroke: "#434e59"
            },
            endpointHoverStyle = {
                fill: "#216477",
                stroke: "#216477"
            },
            // the definition of source endpoints (the small blue ones)
            sourceEndpoint = {
                endpoint: "Dot",
                paintStyle: {
                    stroke: "#434e59",
                    fill: "transparent",
                    radius: 4,
                    strokeWidth: 2
                },
                isSource: true,
                connector: ["Flowchart", {
                    stub: [40, 60],
                    gap: 0,
                    cornerRadius: 5,
                    alwaysRespectStubs: false,
                    midpoint: 0.5
                }],
                connectorStyle: connectorPaintStyle,
                hoverPaintStyle: endpointHoverStyle,
                connectorHoverStyle: connectorHoverStyle,
                dragOptions: {},
                overlays: [
                    ["Label", {
                        location: [0.5, 1.5],
                        label: "Drag",
                        cssClass: "endpointSourceLabel",
                        visible: false
                    }]
                ]
            },
            // the definition of target endpoints (will appear when the user drags a connection)
            targetEndpoint = {
                endpoint: "Dot",
                paintStyle: {fill: "#434e59", radius: 4},
                hoverPaintStyle: endpointHoverStyle,
                maxConnections: -1,
                dropOptions: {hoverClass: "hover", activeClass: "active"},
                isTarget: true,
                overlays: [
                    ["Label", {location: [0.5, -0.5], label: "Drop", cssClass: "endpointTargetLabel", visible: false}]
                ]
            },
            init = function (connection) {
                // connection.getOverlay("label").setLabel(connection.sourceId.substring(15) + "-" + connection.targetId.substring(15));
            };

        var _addEndpoints = function (toId, sourceAnchors, targetAnchors) {
            for (var i = 0; i < sourceAnchors.length; i++) {
                var sourceUUID = toId + sourceAnchors[i];
                instance.addEndpoint("flowchart" + toId, sourceEndpoint, {
                    anchor: sourceAnchors[i], uuid: sourceUUID
                });
            }
            for (var j = 0; j < targetAnchors.length; j++) {
                var targetUUID = toId + targetAnchors[j];
                instance.addEndpoint("flowchart" + toId, targetEndpoint, {anchor: targetAnchors[j], uuid: targetUUID});
            }

        };
        var _addEndpointsTypes = function (id, types) {
            switch (types) {
                case 'start':
                    _addEndpoints(id, ["BottomCenter"], []);
                    break
                case 'process':
                    _addEndpoints(id, ["BottomCenter",], ["TopCenter"]);
                    break
                case 'fork':
                    _addEndpoints(id, ["BottomCenter"], ["TopCenter"]);
                    break
                case 'end':
                    _addEndpoints(id, [], ["TopCenter"]);
                    break
                case 'group':
                    _addEndpoints(id, [], []);
                    break
                default:

            }
        };
        // suspend drawing and initialise.
        let nt = this.el_nodes;
        instance.batch(function () {
            // _addEndpoints("Window2",  ["BottomCenter","LeftMiddle", "RightMiddle"], ["TopCenter"]);
            // _addEndpoints("Window3",  ["BottomCenter","LeftMiddle", "RightMiddle"], ["TopCenter"]);
            // _addEndpoints("Window1",  ["BottomCenter","LeftMiddle", "RightMiddle"], ["TopCenter"]);
            for (let i = 0; i < nt.length; i++) {
                let node = nt[i];
                _addEndpointsTypes("Window" + i, node.type)
            }
            // instance.addGroup({el:"sss",id:"sss"})
            // listen for new connections; initialise them the same way we initialise the connections at startup.
            // instance.bind("connection", function (connInfo, originalEvent) {
            //     init(connInfo.connection);
            // });
            // make all the window divs draggable


            // instance.connect({ uuids: ["Window6TopCenter", "Window2LeftMiddle"], editable: true });
            instance.draggable(jsPlumb.getSelector(".flowchart-demo .window"), {grid: [20, 20]});
            instance.bind("connection", function (connInfo, originalEvent) {
            });

            jsPlumb.connect({
                source: "flowchartWindow1",
                target: "flowchartWindow0",
                newConnection: true
            });
        });
        // instance.addGroup({el:"",id:""});
        jsPlumb.fire("jsPlumbDemoLoaded", instance);


    }


}

export class FlowNodeModel {
    type: string;//start end process group fork
    title: string;
    style: Style

    constructor() {

    }
}

export class Style {
    top: string;
    left: string;
    height: string
    width: string
    transform: string

    constructor() {

    }
}

